package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.DownUpDto;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @package com.heima.wemedia.service.impl
 * @Date 2022/3/1
 * @project heima-leadnews
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String website;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult selectPage(WmNewsPageReqDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getBeginPubDate() != null) {
            queryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            queryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.eq(WmNews::getUserId, user.getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> pages = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(pages, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());
        pageResponseResult.setHost(website);
        return pageResponseResult;
    }

    /**
     * 文章保存修改
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        if (dto == null || dto.getTitle() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setUserId(user.getId());
        //tupe=-1  数据库字段类型为无符号字段 不能出现负数
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        String image = imagesToStr(dto.getImages());
        wmNews.setImages(image);

        saveUpdateWmNews(wmNews);

        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //抽取内容中素材路径
        List<String> list = parseContentImages(dto.getContent());

        //保存素材和文章关系
        saveRelativeInfoForContent(wmNews, list);
        //保存文章封面与文章关系
        saveRelativeInfoForCover(dto, wmNews, list);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送 待审核消息==》队列：{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE);
        return ResponseResult.okResult();

    }

    /**
     * 保存文章封面与素材关系
     *
     * @param dto
     * @param wmNews
     * @param list
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, WmNews wmNews, List<String> list) {
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = list.size();
            //单图
            if (size > 0 && size <= 2) {
                images = list.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }
            //多图
            else if (size > 2) {
                images = list.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(imagesToStr(images));
            }
            updateById(wmNews);
        }
        if (images != null && images.size() > 0) {
            images = images.stream().map(img -> img.replace(website, "").replace(" ", ""))
                    .collect(Collectors.toList());
            saveRelativeInfo(wmNews, images, WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存素材和文章关系
     *
     * @param wmNews
     * @param list
     */
    private void saveRelativeInfoForContent(WmNews wmNews, List<String> list) {
        saveRelativeInfo(wmNews, list, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存素材和文章关系
     *
     * @param wmNews
     * @param url
     * @param type
     */
    private void saveRelativeInfo(WmNews wmNews, List<String> url, Short type) {
        if (url == null||url.size()<=0) {
                return;
        } else {
            List<Integer> materialIds = wmMaterialMapper.selectIds(url, WmThreadLocalUtils.getUser().getId());
            if (CollectionUtils.isEmpty(materialIds) || materialIds.size() < url.size()) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失");
            }
            wmNewsMaterialMapper.saveRelations(materialIds, wmNews.getId(), type);
        }
    }

    /**
     * 抽取内容中素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        return list.stream().filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                .map(m -> (String) m.get("value"))
                .map(url -> url.replace(website, ""))
                .distinct()
                .collect(Collectors.toList());
    }

    //保存或修改文章信息
    private void saveUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);

        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

            updateById(wmNews);
        }


    }

    //解析封面图片引用
    private String imagesToStr(List<String> images) {
        if (images == null) {
            return null;
        }
        return images.stream().map(url -> url.replace(website, ""))
                .collect(Collectors.joining(","));
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult selectOne(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(website);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult deleteNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (!wmNews.getUserId().equals(user.getId())) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        if (WemediaConstants.ALLOW_PASS.equals(wmNews.getStatus()) &&
                WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        removeById(id);
        return ResponseResult.okResult();


    }

    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downorup(DownUpDto dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getEnable() == null || (WemediaConstants.WM_NEWS_UP.equals(dto.getEnable()) && WemediaConstants.WM_NEWS_DOWN.equals(dto.getEnable()))) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "上下架状态设置错误");
        }
        WmNews wmNews = getById(dto.getId());
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不是发布状态，无法上下架");

        }
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);
        if (wmNews.getArticleId() != null) {
            if (dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                        , NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY, wmNews.getArticleId());
            } else {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                        , NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY, wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult();

    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        dto.checkParam();
        Integer page = dto.getPage();
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        List<WmNewsVO> list = wmNewsMapper.findListAndPage(dto);
        Long listCount = wmNewsMapper.findListCount(dto);
        PageResponseResult result = new PageResponseResult(page, dto.getSize(), listCount, list);
        result.setHost(website);
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewSOne(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getUserId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        wmNewsVO.setAuthorName(wmUser.getName());
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(website);
        return result;
    }

    /**
     * 人工审核是否通过
     *
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布");
        }
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        long time = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();
        long remainTime = time - nowTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE, PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId(), (message) -> {
                    message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return message;
                });
        log.info("文章发布通知成功文章id：{}", wmNews.getId());
        return ResponseResult.okResult();
    }

}
